package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private Logger logger=LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBo> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key, String sortBy, Boolean desc) {
        //设置分页条件
        PageHelper.startPage(page,rows);

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //设置过滤条件
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        if(saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }

        //设置排序
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }

        //查询
        Page<Spu> pageInfo= (Page<Spu>) spuMapper.selectByExample(example);

        List<SpuBo> list=pageInfo.getResult().stream().map(spu->{
            SpuBo spuBo = new SpuBo();
            // 属性拷贝
            BeanUtils.copyProperties(spu,spuBo);

            List<String> names = categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(names,"/"));

            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());

            return spuBo;
        }).collect(Collectors.toList());


        //返回查询结果
        return new PageResult<SpuBo>(pageInfo.getTotal(),pageInfo.getPages(),list);
    }

    @Transactional
    public void saveGoods(SpuBo spu) {
        //保存spu
        spu.setSaleable(true);
        spu.setValid(true);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(new Date());
        spuMapper.insert(spu);

        //保存spu详情
        spu.getSpuDetail().setSpuId(spu.getId());
        spuDetailMapper.insert(spu.getSpuDetail());

        saveSkuAndStock(spu.getSkus(),spu.getId());

        sendMessage(spu.getId(),"insert");
    }

    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //查询以前的sku的集合
        List<Sku> skus = this.querySkusBySpuId(spuBo.getId());
        //删除sku和库存数据
        this.deleteSkuAndStock(skus,spuBo.getId());

        // 新增sku和库存
        this.saveSkuAndStock(spuBo.getSkus(),spuBo.getId());

        // 更新spu
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);

        //更新详情
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        sendMessage(spuBo.getId(),"update");
    }

    private void saveSkuAndStock(List<Sku> skus,Long spuId){
        //保存sku和库存信息
        for(Sku sku:skus){
            if(!sku.getEnable()){
                continue;
            }
            //保存sku
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            skuMapper.insert(sku);

            //保存库存信息
            Stock stock = new Stock();
            stock.setStock(sku.getStock());
            stock.setSkuId(sku.getId());
            stockMapper.insert(stock);
        }
    }

    private void deleteSkuAndStock(List<Sku> skus,Long spuId){
        if(!CollectionUtils.isEmpty(skus)){
            List<Long> ids=skus.stream().map(sku-> sku.getId()).collect(Collectors.toList());

            //删除库存
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId",ids);
            stockMapper.deleteByExample(example);

            //删除skus
            Sku sku = new Sku();
            sku.setSpuId(spuId);
            skuMapper.delete(sku);
        }
    }

    public List<Sku> querySkusBySpuId(Long spuId) {
        //查询sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);

        //查新库存
        for(Sku s:skus){
            s.setStock(stockMapper.selectByPrimaryKey(s.getId()).getStock());
        }
        return skus;
    }

    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return spuDetailMapper.selectByPrimaryKey(spuId);
    }

    @Transactional
    public void deleteGoods(Long id) {
        List<Sku> skus = this.querySkusBySpuId(id);

        //删除sku和库存数据
        this.deleteSkuAndStock(skus,id);

        //删除spu
        spuMapper.deleteByPrimaryKey(id);

        //删除详情
        spuDetailMapper.deleteByPrimaryKey(id);

        sendMessage(id,"delete");
    }

    public void upperAndLowerShelves(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    public Spu querySpuById(Long id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            // 交换机名称,routeKey名称,消息
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }

    /**
     * 根据skuid 减库存
     * @param id
     * @param num
     * @return
     */
    public boolean deleteStocckBySkuId(Long id ,Integer num) {
        Stock stock = this.stockMapper.selectByPrimaryKey(id);

        Integer stockNum = stock.getStock();
        if (stockNum>num && num >= 1) {
            Integer nowNum = stockNum - num;
            stock.setStock(nowNum);
            this.stockMapper.updateByPrimaryKey(stock);
            return true ;
        }
        return false;
    }

    public Sku querySkuById(Long id) {
        return skuMapper.selectByPrimaryKey(id);
    }

    public Cart querySaleable(Long skuId) {
        Sku sku = skuMapper.selectByPrimaryKey(skuId);
        Spu spu = spuMapper.selectByPrimaryKey(sku.getSpuId());
        Cart cart= new Cart();
        cart.setCurrentPrice(sku.getPrice());
        cart.setSaleable(spu.getSaleable());
        return cart;
    }

}
